package com.zb.tcp.rpc.server;

import java.io.File;
import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;

import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.ipc.NettyServer;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.generic.GenericResponder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.zb.entity.base.JsonCommon;
import com.zb.entity.base.JsonForList;
import com.zb.entity.base.OmsCommonParam;
import com.zb.entity.charger.OmsChargerBuildApply;
import com.zb.entity.station.OmsStation;
import com.zb.service.sys.ChargerService;
import com.zb.service.sys.StationService;
import com.zb.util.StringUtil;
import com.zb.util.OmsConstant.MsgCodeEnum;

/**
 * @Title: OMS服务器提供的RPC服务
 * @author pengyu   
 * @date 2016-1-15
 */
//@Component
public class OmsRPCServer{
	private Logger log = LoggerFactory.getLogger(OmsRPCServer.class);
	
	@Autowired
	ASRPCHandler handler;
	@Autowired
	ChargerService chargerService;
	@Autowired
	StationService stationService;
	
	@Value(value="${rpc.self.port}")
	private int port;
	@Value(value="${omsFileName}")
	private String protocolFile;
	private static Server server;
	
	public OmsRPCServer(){
	}

    @PostConstruct
	public void init(){
    	try {
    		String filePath = this.getClass().getResource(protocolFile).getPath();
    		Protocol protocol = Protocol.parse(new File(filePath));
            server = new NettyServer(
            		new AvroGenericResponder(protocol),
            		new InetSocketAddress(this.port));

            server.start();
        } catch (Exception e) {
        	log.info("运营管理服务器RPC服务初始化失败", e);
        }
    }
    
    public class AvroGenericResponder extends GenericResponder{
    	public AvroGenericResponder(Protocol protocol) {
            super(protocol);
        }
    	
        @SuppressWarnings("rawtypes")
		@Override
    	public Object respond(Message message, Object request) throws Exception {
        	log.info("运营管理服务器接收到RPC请求" + message.getName());
        	GenericRecord req = (GenericRecord) request;
        	String messageName = message.getName();
        	JsonForList json = new JsonForList() ;
        	if(StringUtil.isBlank(messageName)){
        		json.setCode("10303101");
        		json.setMsg("缺少参数字段:方法名");
        		return json;
        	}
        	switch(messageName){
        		case "getStationList"://4.1. 获取站点简要信息（2001）  4.2. 获取站点信息（2002）4.5. 获取多站详细信息（2005）
                	try{
                		OmsStation omsStation = JSON.parseObject(req.get("omsStation").toString(), OmsStation.class);
                		json = stationService.getStationList(omsStation, null);
//            			return JsonForStationList;
            		} catch(Exception e){
            			log.error("获取站点信息异常", e);
            			json.setCode("10301101");
            			json.setMsg("获取站点信息异常");
            			return json;
            		}
        			break;
        		case "getStationListByPage":
        			try{
                		OmsStation omsStation = JSON.parseObject(req.get("omsStation").toString(), OmsStation.class);
                		//如果某些参数为空，就设置默认值
                		int pageNo = Integer.valueOf(req.get("pageNo").toString());
                		int pageSize =Integer.valueOf(req.get("pageSize").toString());
                		String sortName = JSON.parseObject(req.get("sortName").toString(), String.class);
                		int sortVal = Integer.valueOf(req.get("sortVal").toString());
                		if(!StringUtil.isNumeric(req.get("pageNo").toString())||!StringUtil.isNumeric(req.get("pageSize").toString())||!StringUtil.isNumeric(req.get("pageSize").toString())){
                			
                		}
                		json = stationService.getStationListByPage(omsStation, pageNo, pageSize, sortName, sortVal, null);
//            			return JsonForStationList;
            		} catch(Exception e){
            			log.error("获取站点信息异常", e);
            			json.setCode("10301101");
            			json.setMsg("获取站点信息异常");
            			return json;
            		}
        			break;
        		case "5":
        			break;
        		/**********perlin 20160324 add begin***************************/
        		case "buildCharger":
        		case "cooperationType":
        		case "applyCooperation":
        		case "updateMapDataPackage":
        		case "getMapDataPackage":
        		case "getFreeChargerByStationId":
        		case "getChargerListByStationId":
        		case "getChargerDetailByChargerId":
        		case "stationErrorInfo":
        		case "getUsedUserIdByStationId":
        		case "uploadImage":
        		case "chargeReservation":
        		case "getReservationDiscount":
        		case "cancelReservation":
        		case "startCharge":
        		case "closeCharge":
        		case "getReservationListByPage":
        		case "getReservationDetailById":
        		case "getChargeListByPage":
        		case "getChargeDetailById":
        		case "getErrorCode":
        		case "getCurrentUseBookOrChargeNumbers":
        		case "getStationDetailByStationId":
        		case "getChargerPortsByChargerId":
        		case "getChargerPortStatus":
        		case "getChargerDetailByQrCode":
        		case "getQiniuyunUpToken":
        		case "getIdOfNowStatusByChargeridAndPortid":
        		case "startChargeByQrCode":	
        		case "getChargeInfoAndBespeakInfoByUserPayCard":
        		case "getBespeakDetailInfoByOrderNo":
        		case "getChargeDetailInfoByOrderNo":
        		case "getChargerRate":
        		case "deleteQiniuyunImage":
        		case "getExternalStation":
        		case "getStationByName":
        		case "getStationByLocation":
        		case "getStationsByCoord":
        		case "scoreStation":
        			return handler.doProcess(messageName,req);
        		/**********perlin 20160324 add end***************************/
        		default:
        			break;
        	}
            return json;
        }
    }
    

}